<?php

namespace App\Providers;

use App\Http\Common\Globals;
use App\Http\Common\MyUtils;
use App\Http\Common\MyValidator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
class AppServiceProvider extends ServiceProvider
{
    /**
     * 每次都会运行到这里，可以在这里注册任何的服务
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
        $this->validatorExtend();
        $this->listenWriteDbLog();
    }

    /**
     * 监听写数据库日志
     */
    public function listenWriteDbLog(){
        // error_reporting(E_ALL ^ E_NOTICE);// 降低报错等级
        // 监听所有的sql语句 将其写到日志里面，方便日后查看
        DB::listen(function ($query) {
            if (Globals::$writeLog) {
                $sql = $query->sql;
                $bindings = $query->bindings;
                $path = base_path("storage/logs/sql/");
                // 文件夹不存在就创建
                if (!file_exists($path))  MyUtils::mkdirs($path);
                $content_ = "";
                //写入sql
                if ($bindings) {
                    if (!Globals::$temp){
                        Globals::$temp = time().Str::random(30);
                    }
                    if (is_string(Globals::$temp)){
                        $content_ = "unqiueCode: ".Globals::$temp."\r\n";
                    };
                    file_put_contents($path.date("Y-m-d-H") .'-sql.log', "[" . date("Y-m-d H:i:s") . "]" . $sql . "\r\nparmars:" . json_encode($bindings, 320) . "\r\n$content_\r\n", FILE_APPEND);
                } else {
                    if (is_string(Globals::$temp)){
                        $content_ = "unqiueCode: ".Globals::$temp."\r\n";
                    };
                    file_put_contents($path.date("Y-m-d-H") .'-sql.log', "[" . date("Y-m-d H:i:s") . "]" . $sql . "\r\n$content_\r\n", FILE_APPEND);
                }
            }
        });
    }

    /**
     * 新增自定义验证规则
     */
    public function validatorExtend(){
        MyValidator::getInstance()->register();
    }

}
